import threading
import os
import shutil
import pyautogui as pg
import pandas as pd
from time import sleep
from platform import system
from pynput import keyboard
from PyQt5.QtWidgets import QMainWindow
from UI.ui_main_window import Ui_MainWindow
from service.utils import create_path, rect_img
from source.image_process.snapshot import gnome_screenshot
from source.image_process.case_info import case_info
from source.image_process.algo_select import compare_algo

pg.FAILSAFE = False
play_flag = True


class Runner(QMainWindow, Ui_MainWindow):
    def __init__(self, data_path, image_path):
        super(Runner, self).__init__()
        self.setupUi(self)
        self.data_path = data_path
        self.image_path = image_path

    def select_screenshot(self, image_name):
        if system() == 'Windows':
            pass
        elif system() == 'Linux':
            t = gnome_screenshot(image_name)
            return t

    def clear_data(self, data_path):
        shutil.rmtree(data_path)
        create_path(data_path)

    def on_press(self, key):
        if key == keyboard.Key.esc:
            global play_flag
            play_flag = False
            return False

    def on_release(self, key):
        if key == keyboard.Key.esc:
            return False

    def exit_replay(self):
        with keyboard.Listener(on_press=self.on_press, on_release=self.on_release) as listener:
            listener.join()

    def run(self):
        global play_flag
        play_flag = True
        if os.path.exists(self.data_path) and os.path.isfile(self.data_path):
            record_data = pd.read_csv(self.data_path, index_col=0)
            all_step = record_data.shape[0]
            e = threading.Thread(target=self.exit_replay)
            e.start()
            # os.system('wheeldist')
            if '比对区域' not in record_data.columns.to_list():
                record_data.columns.to_list().insert(4, '比对区域')
                record_data.reindex(columns=record_data.columns.to_list())
                record_data.insert(loc=4, column='比对区域', value='nan')
            if '相似度' not in record_data.columns.to_list():
                record_data.columns.to_list().insert(5, '相似度')
                record_data.reindex(columns=record_data.columns.to_list())
                record_data.insert(loc=5, column='相似度', value='nan')
            if '结果' not in record_data.columns.to_list():
                record_data.columns.to_list().insert(6, '结果')
                record_data.reindex(columns=record_data.columns.to_list())
                record_data.insert(loc=6, column='结果', value='nan')
            record_data.to_csv(
                self.data_path, columns=record_data.columns.to_list(), encoding='utf_8_sig')
            for run_step in range(0, record_data.shape[0]):
                click_delay = record_data.iloc[run_step, 0]
                press_type = record_data.iloc[run_step, 1]
                event_type = record_data.iloc[run_step, 2]
                input_data = eval(
                    record_data.iloc[run_step, 3].replace("", ""))
                sleep(click_delay/1000.0)
                if play_flag == False:
                    break
                if event_type == 'mouse move':
                    pg.moveTo(
                        int(input_data[0]), int(input_data[1]), tween=pg.easeInBounce)
                if event_type == 'mouse left down':
                    pg.mouseDown(
                        int(input_data[0]), int(input_data[1]), button='left')
                if event_type == 'mouse left up':
                    next_up = run_step+2
                    if next_up < all_step:
                        next_press_type = record_data.iloc[next_up, 1]
                        next_event_type = record_data.iloc[next_up, 2]
                        next_input_data = eval(
                            record_data.iloc[next_up, 3].replace("", ""))
                        if event_type == next_event_type and input_data == next_input_data:
                            run_step = next_up
                            pg.click(int(input_data[0]), int(
                                input_data[1]), clicks=2)
                    pg.mouseUp(int(input_data[0]), int(
                        input_data[1]), button='left')
                    image_file = os.path.join(
                        self.image_path, str(run_step+1) + '.png')
                    self.select_screenshot(image_file)
                if event_type == 'mouse right down':
                    pg.mouseDown(
                        int(input_data[0]), int(input_data[1]), button='right')
                if event_type == 'mouse right up':
                    pg.mouseUp(int(input_data[0]), int(
                        input_data[1]), button='right')
                    image_file = os.path.join(
                        self.image_path, str(run_step+1) + '.png')
                    self.select_screenshot(image_file)
# -------------------------------------------------------------------------------------------------------
                if event_type == 'mouse wheel down':
                    if click_delay < 10:
                        run_step += 2
                        cmd = 'xdotool click 5 sleep '+str(click_delay/1000)
                        os.system(cmd)
                if event_type == 'mouse wheel up':
                    if click_delay < 10:
                        run_step += 2
                        cmd = 'xdotool click 4 sleep '+str(click_delay/1000)
                        os.system(cmd)
# -------------------------------------------------------------------------------------------------------
                if event_type == 'mouse middle down':
                    pg.mouseDown(button='middle')
                if event_type == 'mouse middle up':
                    pg.mouseUp(button='middle')
                if event_type == 'key down':
                    pg.keyDown(input_data[0])
                if event_type == 'key up':
                    pg.keyUp(input_data[0])

    def screenshot(self, screenshot_type, record_image_path, replay_image_path=None):
        if screenshot_type == 1:  # 录制截图
            self.clear_data(record_image_path)
            self.run()
            ret = case_info(self.data_path, record_image_path)
            if isinstance(ret, list):
                return True
            else:
                return False
        elif screenshot_type == 2:  # 回放
            print("回放比对图片目录：", record_image_path, replay_image_path)
            self.clear_data(replay_image_path)
            self.run()
            image_name = case_info(self.data_path, replay_image_path)
            if isinstance(image_name, list):
                compare_algo(record_image_path, replay_image_path,
                             self.data_path, image_name, 1)
                return True
            else:
                return False
